#!/bin/bash

# 这是一个自动化脚本，用于完整地设置Python环境、安装所有依赖，并开始为OpenHarmony代码库构建RAG索引。

# 使用 set -e 命令，确保脚本中任何命令执行失败时，脚本会立即停止。
set -e

# --- 第1步：确保在正确的目录中 
# 该脚本应从您的项目根目录（例如 /home/lmxmxxf/K1_OH5.0/source）运行
echo "INFO: Executing in current directory: $(pwd)"

# --- 第2步：创建并激活Python虚拟环境 ---
echo "INFO: Creating and activating Python virtual environment at ./.venv"
python3 -m venv .venv
source .venv/bin/activate

# --- 第3步：安装系统级编译工具 ---
echo "INFO: Installing build-essential for compiling Python packages..."
echo "INFO: This may ask for your password."
sudo apt-get update && sudo apt-get install -y build-essential

# --- 第4步：安装所有必需的Python依赖包 ---
echo "INFO: Installing all required Python dependencies..."
pip install llama-index-core chromadb sentence-transformers transformers torch llama-index-llms-ollama llama-index-vector-stores-chroma llama-index-embeddings-huggingface tree-sitter tree_sitter_language_pack

echo "SUCCESS: All dependencies installed successfully."

# --- 第5步：清理旧数据库并开始构建 ---
# 这是最耗时的一步，它将开始处理代码并构建知识库。
echo "INFO: Deleting old database (if exists) for a clean build..."
rm -rf ./oh_chroma_db
echo "INFO: Starting the indexing process. This will take a very long time..."
./.venv/bin/python3 build_rag_index.py

echo "SUCCESS: Indexing complete!"

# --- 第6步：提示如何进行查询 ---
# 脚本到此执行完毕。下面的指令提示您如何手动开始查询。
echo "INFO: You can now start the query engine by running the following commands:"
echo "      source .venv/bin/activate"
echo "      python3 query_rag.py \"Your Question Here\""